require([ 'zTreeCheckbox', 'select2' ], function() {
	var userInfo = commonFun.execParentMethod("getUserInfo");
	var isAdminRole = userInfo.isAdminRole;
	// 初始化查询条件
	var $sysRoleTree = $("#sysRoleTree");
	var ztree = null;// 左侧树对象
	$("#selForm").initForm();
	commonFun.authorityLoad($("#shortmenu"));

	function resize() {
		$("#left").height($(window).height());
		$("#right").height($(window).height());
		//左侧树高度
		$sysRoleTree.height($(window).height() - 55);
	}
	$(window).on('resize', resize).trigger('resize');

	initSysRoleTree();
	
	// 初始化样式 begin
	$('#tree').parent().css({
		height : $(window).height() - 122,
		width : '100%'
	});
	
	var setting = {
		check : {
			enable : true,
			chkboxType : {
				"Y" : "ps",
				"N" : "ps"
			}
		},
		data : {
			keep : {
				leaf : false,
				parent : false
			},
			key : {
				name : "organName"
			},
			simpleData : {
				enable : true,
				idKey : "organId",
				pIdKey : "parentOrganId",
				rootPid : null
			}
		},
		view : {
			showIcon : false
		},
		callback : {
			onClick : function(event, treeId, treeNode, clickFlag) {
			}
		}
	};

	/**
	 * 设置图标
	 */
	function setNodeIcon(zNodes) {
		$.each(zNodes,
				function(index, item) {
					item.icon = $.getProjectName()
							+ "/content/images/role-icon_03.png";
				});
		return zNodes;
	}

	/**
	 * 根据节点高亮标志，渲染树节点
	 */
	function getFontCss(treeId, treeNode) {
		return (!!treeNode.highlight) ? {
			color : "#A60000",
			"font-weight" : "bold"
		} : {
			color : "#333",
			"font-weight" : "normal"
		};
	}

	/**
	 * 获得根节点并选中根节点
	 */
	function getAndSelectRootNode() {
		var node = sysRoleTreeObj.getNodesByFilter(function(node) {
			return node.level == 0;
		}, true);
		sysRoleTreeObj.selectNode(node, false);
		sysRoleTreeClick(null, node.id, node, true);
	}

	/**
	 * 点击树节点
	 */
	function sysRoleTreeClick(event, treeId, treeNode, clickFlag) {
        $("#selResType").select2("val","RES00001");
		$("#corpId").val(treeNode.corpId);
		$("#roleId").val(treeNode.id);
		$("#level").val(treeNode.level);
//		$("#opr").val("clickTree");

		// 自己的角色不允许修改
		if (isAdminRole === "0" && $("#level").val() === "0") {
			$("#saveAuthority").hide();
		} else {
			$("#saveAuthority").show();
		}
		var treeNodes;
		$.ajaxExt({
			async : true,
			url : "/sysAuthorityFunc/getResTreeData.htm",
			data : {
				"corpId" : treeNode.corpId,
				"roleId" : treeNode.id,
				"roleType" : userInfo.roleType,
				"selResType" : $("#selResType").val(),
				"level" : treeNode.level
			}
		}).done(function(data) {
			if (!data) {
				data = [];
			}
			treeNodes = setNodeIcon(data);
			ztree = $.fn.zTree.init($("#tree"), setting, treeNodes);
			if (ztree) {
				var nodes = ztree.getNodes(), root = nodes[0];
				ztree.expandNode(root, true, false, false);// 默认展开根节点
			}
			reloadTree();
		});
	}

	/**
	 * 获得节点数据，并且生成左侧的树
	 */
	function initSysRoleTree() {
		$.ajaxExt({
			async : true,
			url : "/sysRole/getSysRoleByName.htm"
		}).done(function(data) {
			if (!data) {
				data = [];
			}
			zNodes = setNodeIcon(data);
			// 树的参数配置
			var setting = {
				data : {
					key : {
						name : "name"
					},
					simpleData : {
						enable : true,
						idKey : "id",
						pIdKey : "parentRoleId",
						rootPId : 0
					}
				},
				view : {
					showIcon : true,
					fontCss : getFontCss
				},
				callback : {
					onClick : sysRoleTreeClick
				}
			};
			// 生成树
//			sysRoleTreeObj = $.fn.zTree.init($sysRoleTree, setting, zNodes);
			sysRoleTreeObj = $sysRoleTree.createTree(setting, data, {search: $('#search-text')});
			sysRoleTreeObj.setting.view.expandSpeed = "";
			sysRoleTreeObj.expandAll(true);
			sysRoleTreeObj.setting.view.expandSpeed = "fast";
			getAndSelectRootNode();// 选中根节点，触发事件
		});
	}

	/**
	 * 根据指定角色刷新树状图
	 */
	function reloadTree() {
		// 读取数据 重载ztree
		$.ajaxExt({
			url : "/sysAuthorityFunc/getCheckedResData.htm",
			data : {
				"roleId" : $("#roleId").val()
			}
		}).done(function(data) {
			// 全部取消勾选
			ztree.checkAllNodes(false);
			// 根据读取数据设置勾选
			if(data && data.length > 0){
                $.each(data, function(i, ctx) {
                    var node = ztree.getNodeByParam("organId", ctx.resDataId);
                    if (node) {
                        ztree.checkNode(node);
                    }
                });
            }
		});
	}

	// 点击保存资源信息
	$("#saveAuthority").on("click", function() {
		var dataIds = [], isFulls = [];
		// 获取选中节点的id
		var nodes = ztree.getCheckedNodes(true);
		for ( var i in nodes) {
			dataIds.push(nodes[i].organId);
			// 是否全选
			if (nodes[i].getCheckStatus().half) {
				isFulls.push(0);
			} else {
				isFulls.push(1);
			}
		}
		var loadMask = $.createMask();
		$.ajaxExt({
			url : "/sysAuthorityFunc/saveResAuthority.htm",
			data : {
				"dataIds" : dataIds,
				"isFulls" : isFulls,
				"dataType" : $("#selResType").val(),
				"roleId" : $("#roleId").val()
			}
		}).done(function() {
			$.messager.alert("保存", "保存成功!", "msg", function() {
				loadMask.remove();
				// 重新载入ztree
				reloadTree();
				// 刷新
				ztree.refresh();
			});
		});
	});

	$("#selResType").change(function(){
		//TODO
        $.ajaxExt({
            async : true,
            url : "/sysAuthorityFunc/getResTreeData.htm",
            data : {
                "corpId" : $("#corpId").val(),
                "roleId" : $("#roleId").val(),
                "roleType" : userInfo.roleType,
                "selResType" : $("#selResType").val(),
                "level" : $("#level").val()
            }
        }).done(function(data) {
            if (!data) {
                data = [];
            }
            treeNodes = setNodeIcon(data);
            ztree = $.fn.zTree.init($("#tree"), setting, treeNodes);
            if (ztree) {
                var nodes = ztree.getNodes(), root = nodes[0];
                ztree.expandNode(root, true, false, false);// 默认展开根节点
            }
            reloadTree();
        });
	});

    $("#selResType").select2("val","RES00001");
	// 全选事件
	// $("#chkAll").on("click", function() {
	// 	ztree.checkAllNodes(true);
	// });
	// 反向全选事件
	// $("#unchkAll").on("click", function() {
	// 	ztree.checkAllNodes(false);
	// });
});